<template>
    <div class="check-container">
        <div class="check-title">
            系统只会记录上班/下班的第一条打卡数据，请注意打卡时间
        </div>
        <!--开启摄像头-->
        <!--        <img @click="callCamera" :src="headImgSrc" alt="摄像头" height="100px" width="100px">-->
        <!--canvas截取流-->
        <canvas ref="canvas" width="640" height="480" v-show="false"></canvas>
        <!--图片展示-->
        <video ref="video" width="640" height="480" autoplay></video>
        <!--确认-->
        <br>
        <br>
        <el-button size="medium" type="primary" :disabled="disabled" :loading="loading" @click="photograph(1)">上班打卡
        </el-button>
        <el-button size="medium" type="success" :disabled="disabled" :loading="loading" @click="photograph(2)">下班打卡
        </el-button>
        <br>
        <br>
        <el-alert
                :title="title"
                :type="success"
                v-show="show"
                effect="dark"
                show-icon>
        </el-alert>
    </div>
</template>
<script>
    import service from "../../utils/request";

    export default {
        data() {
            return {
                disabled: false,
                loading: false,
                show: false,
                title: '',
                success: 'success',
                headImgSrc: require('@/assets/image/photograph.png')
            }
        },
        methods: {
            // 调用摄像头
            callCamera() {
                // H5调用电脑摄像头API
                navigator.mediaDevices.getUserMedia({
                    video: true
                }).then(success => {
                    // 摄像头开启成功
                    this.$refs['video'].srcObject = success
                    // 实时拍照效果
                    this.$refs['video'].play()
                }).catch(error => {
                    console.error('摄像头开启失败，请检查摄像头是否可用！')
                })
            },
            // 拍照
            photograph(status) {
                this.loading = true
                let ctx = this.$refs['canvas'].getContext('2d')
                // 把当前视频帧内容渲染到canvas上
                ctx.drawImage(this.$refs['video'], 0, 0, 640, 480)
                // 转base64格式、图片格式转换、图片质量压缩
                let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7)

                // 由字节转换为KB 判断大小
                let str = imgBase64.replace('data:image/jpeg;base64,', '')
                let strLength = str.length
                let fileLength = parseInt(strLength - (strLength / 8) * 2)
                // 图片尺寸  用于判断
                let size = (fileLength / 1024).toFixed(2)
                console.log(size)
                // 上传拍照信息  调用接口上传图片
                let formData = new FormData();
                formData.append('userId', JSON.parse(localStorage.getItem("userInfo")).id)
                formData.append('base64', imgBase64);
                formData.append('status', status)
                //上班打卡
                service.post('/check/face', formData).then(res => {
                    if (res.status == '1') {
                        this.show = true
                        this.success = 'success'
                        this.title = '打卡成功，请勿重复打卡'
                        this.disabled = true
                    } else {
                        this.show = true
                        this.title = '人脸校验未通过，请重试'
                        this.success = 'warning'
                    }
                    this.loading = false
                }).catch(err => {
                    this.show = true
                    this.loading = false
                    this.title = '请检查网络连接'
                    this.success = 'error'
                })
                // 保存到本地
                // let ADOM = document.createElement('a')
                // ADOM.href = this.headImgSrc
                // ADOM.download = new Date().getTime() + '.jpeg'
                // ADOM.click()
            },
            // 关闭摄像头
            closeCamera() {
                if (!this.$refs['video'].srcObject) return
                let stream = this.$refs['video'].srcObject
                let tracks = stream.getTracks()
                tracks.forEach(track => {
                    track.stop()
                })
                this.$refs['video'].srcObject = null
            }
        }, mounted() {
            this.callCamera()
        }
    }
</script>
<style scoped>
    .check-container {
        width: 100%;
        height: 100%;
        background-color: whitesmoke;
        text-align: center;
    }

    .check-container .check-title {
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
        background-color: whitesmoke;
        margin-bottom: 20px;
        font-weight: bold;
    }
</style>
